package com.sdyd.antivirus.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.sdyd.antivirus.dao.AnswerInfoMapper;
import com.sdyd.antivirus.dao.QuestionInfoMapper;
import com.sdyd.antivirus.dao.QuestionnaireInfoMapper;
import com.sdyd.antivirus.model.AnswerInfo;
import com.sdyd.antivirus.model.QuestionInfo;
import com.sdyd.antivirus.model.QuestionnaireBaseInfo;
import com.sdyd.antivirus.model.QuestionnaireInfo;
import com.sdyd.antivirus.service.CustomizeQuestionnaireService;
import com.sdyd.antivirus.utils.UUIDUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "CustomizeQuestionnaireService")
public class CustomizeQuestionnaireServiceImpl implements CustomizeQuestionnaireService {
    Logger logger= LoggerFactory.getLogger(CustomizeQuestionnaireServiceImpl.class);


    @Autowired
    private QuestionnaireInfoMapper questionnaireInfoMapper;

    @Autowired
    private QuestionInfoMapper questionInfoMapper;

    @Autowired
    private AnswerInfoMapper answerInfoMapper;

    public JSONObject getDetailQuestionnaire(String groupId, String questionnaireId) {
        JSONObject json = new JSONObject();
        try {
            // for test
//            groupId = "1";
//            questionnaireId = "1";
            logger.info("groupId: " + groupId +", questionnaireId: " + questionnaireId);

            QuestionnaireInfo questionnaireInfo = questionnaireInfoMapper.selectByIdAndGroup(questionnaireId, groupId);

            if (questionnaireInfo == null) {
                json.put("success", false);
                return json;
            }

            json.put("title", questionnaireInfo.getTitle());
            // 取到 questionnaire_info 表中的 questionIds
            List<String> ids = JSONArray.parseArray(questionnaireInfo.getQuestionIds(), String.class);

            // 查询得到 questionInfo 的详细信息，并且把结果序列化成 json
            List<QuestionInfo> questions = questionInfoMapper.selectByIds(ids);
            JSONArray jQuestions = new JSONArray();
            for (QuestionInfo question: questions) {
                jQuestions.add(question.toJson());
            }

            json.put("question", jQuestions);
            json.put("success", true);

        }catch (Exception e) {
            e.printStackTrace();
            json = new JSONObject();
            json.put("success",false);
            json.put("msg", "查询失败，请联系管理员，谢谢使用");
        }

        return json;
    }

    public JSONObject saveQuestionnaire(String jsonData){
        JSONObject json = new JSONObject();
        try {
            //jsonData = "{\"used\":0,\"title\":\"第一份问卷（测试）\",\"question\":[{\"id\":\"\",\"title\":\"问题1\",\"type\":\"radio\",\"need\":true,\"options\":[\"单选问题选项1\",\"单选问题选项2\"],\"isEdit\":false,\"answers\":[],\"answer\":\"\"},{\"id\":\"\",\"title\":\"问题2\",\"type\":\"checkbox\",\"need\":true,\"options\":[\"多选问题选项1\",\"多选问题选项2\"],\"isEdit\":false,\"answers\":[],\"answer\":\"\"},{\"id\":\"\",\"title\":\"问题3\",\"type\":\"date\",\"need\":true,\"options\":[],\"isEdit\":false,\"answers\":[],\"answer\":\"\"},{\"id\":\"\",\"title\":\"问题4\",\"type\":\"textarea\",\"need\":true,\"options\":[],\"isEdit\":false,\"answers\":[],\"answer\":\"\"}],\"groupId\":\"10bdfb59503d4b469aab4f12d135778e\"}";
            logger.info("jsonData: " + jsonData);
            JSONObject object = JSONObject.parseObject(jsonData);

            String groupId = object.getString("groupId");
            String id = object.getString("id");
            String title = object.getString("title");

            if (groupId == null || title == null) {
                json.put("msg", "请求参数不完整");
                json.put("success", false);
                return json;
            }

            // 不属于新增问卷
            if(id != null && id.length() != 0) {
                QuestionnaireInfo questionnaireInfo = questionnaireInfoMapper.selectByIdAndGroup(id, groupId);
                if (questionnaireInfo == null) {
                    json.put("msg", "无此调查问卷");
                    json.put("success", false);
                    return json;
                }

                int answerCount = questionnaireInfo.getAnswerCount();
                // 如果问卷没被人答过，删除掉原来所有的题目
                if (answerCount == 0) {
                    List<String> ids = JSONArray.parseArray(questionnaireInfo.getQuestionIds(), String.class);
                    questionInfoMapper.deleteByIds(ids);
                }

                questionnaireInfoMapper.deleteByPrimaryKey(questionnaireInfo.getId());
            }

            JSONArray jQuestionIds = new JSONArray();

            // 从上传 json 中取出 question 字段，获取有效的 question，入库
            JSONArray jQuestions = object.getJSONArray("question");
            List<QuestionInfo> questions = new ArrayList<>();
            for (int i = 0; i < jQuestions.size(); i++) {
                QuestionInfo info = QuestionInfo.allocByJson(jQuestions.getJSONObject(i));
                if (info != null) {
                    jQuestionIds.add(info.getId());
                    questions.add(info);
                }
            }

            // 需要修改调查问卷表以及调查问卷问题表
            QuestionnaireInfo addRecord = new QuestionnaireInfo();
            addRecord.setId(UUIDUtils.getUUID());
            addRecord.setGroupId(groupId);
            addRecord.setTitle(title);
            addRecord.setUsed("0");
            addRecord.setAnswerCount(0);
            addRecord.setQuestionIds(jQuestionIds.toString());
            questionnaireInfoMapper.insert(addRecord);

            questionInfoMapper.insertByList(questions);

            json.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            json = new JSONObject();
            json.put("success", false);
            json.put("msg", "保存失败，请联系管理员，谢谢使用");
        }

        return json;
    }

    public JSONObject publishQuestionnaire(String jsonData){
        JSONObject json = new JSONObject();

        try {
//            jsonData = "{ \n" +
//                    "\t'groupId': '1',\n" +
//                    "\t'id' : '1',\n" +
//                    "\t'title': '疫情统计', \n" +
//                    "\t'ussed': '0'\n" +
//                    "}";
            logger.info("jsonData: " + jsonData);
            JSONObject object = JSONObject.parseObject(jsonData);

            String groupId = object.getString("groupId");
            String id = object.getString("id");
            String used = object.getString("used");

            if (groupId == null || id == null || used == null) {
                json.put("msg", "请求参数不完整");
                json.put("success", false);
                return json;
            }

            questionnaireInfoMapper.updateUsedByIdAndGroup(used, id, groupId);
            json.put("success", true);
        }catch (Exception e) {
            e.printStackTrace();
            json.put("success", false);
            json.put("msg", "请求失败，请联系管理员，谢谢使用");
        }

        return json;
    }

    @Override
    public JSONObject submitQuestionnaire(String jsonData) {
        JSONObject data = new JSONObject();
        try {
            //将要保存到数据库的实体类
            AnswerInfo answerInfo = AnswerInfo.allocByJson(JSONObject.parseObject(jsonData));

            if (answerInfo != null) {
                answerInfoMapper.insert(answerInfo);
            }
            else {
                data.put("success", false);
                data.put("msg", "参数解析失败");
                return data;
            }
            data.put("success", true);

        }catch(Exception e) {
            e.printStackTrace();
            logger.error("提交失败："+e.getMessage());
            data.put("success", false);
            data.put("msg","提交失败,请联系管理员，谢谢使用");
        }
        return data;
    }

    /**
     * 根据组织 id获取问卷基本信息
     * @param groupId  组织id
     * @return JSONObject,最终的返回结果
     */
    @Override
    public JSONObject getQuestionnaires(String groupId){
        JSONObject data = new JSONObject();
        List<QuestionnaireBaseInfo> resultList = new ArrayList<QuestionnaireBaseInfo>();
        try {
            resultList = questionnaireInfoMapper.getQuestionnairesByGroupId(groupId);
            data.put("success", true);
            data.put("questionnaire", resultList);
        }catch(Exception e) {
            e.printStackTrace();
            logger.error("查询问卷基本信息失败："+e.getMessage());
            data.put("success", false);
            data.put("msg","查询失败，请联系管理员，谢谢使用");
        }
        return data;
    }

    /**
     * 根据组织id与问卷id查询对应的问卷,如果问卷的answer_count大于0，仅仅删除问卷；如果等于0，删除问卷以及问卷题目
     *
     * @param groupId 组织id（groupId）与
     * @param questionnaireId 问卷id
     * @return JSONObject 代表是否删除成功
     */
    @Override
    public JSONObject delQuestionnaire(String groupId, String questionnaireId){
        JSONObject data = new JSONObject();
        data.put("success", true);
        try {
            //通过组织id和问卷id获取该问卷
            QuestionnaireInfo questionnaireInfo = questionnaireInfoMapper.selectByIdAndGroup(questionnaireId, groupId);
            if(questionnaireInfo != null) {
                //如果等于0，说明当前问卷没有被使用，删除问卷以及问卷对应的问题 ；否则，说明当前问卷被使用，仅仅删除问卷信息
                int answerCount = questionnaireInfo.getAnswerCount();
                questionnaireInfoMapper.deleteByPrimaryKey(questionnaireId);
                if(answerCount == 0) {
                    String questionIds = questionnaireInfo.getQuestionIds();
                    List<String> ids = JSONArray.parseArray(questionIds, String.class);
                    //如果问卷不存在对应的问题，则不执行问题的删除
                    if(CollectionUtils.isNotEmpty(ids)) {
                        questionInfoMapper.deleteByIds(ids);
                    }
                }
            }else {
                logger.error("删除失败，找不到对应的问卷信息");
                data.put("success", false);
                data.put("msg","删除失败，找不到对应的问卷信息,请联系管理员，谢谢使用");
            }
        }catch(Exception e) {
            e.printStackTrace();
            logger.error("删除失败："+e.getMessage());
            data.put("success", false);
            data.put("msg","删除失败,请联系管理员，谢谢使用");
        }
        return data;
    }
}
